//
//  CDVWechat.m
//  cordova-plugin-adam-wechat
//
//
//

#import "CDVEnterpriseWechat.h"

static int const MAX_THUMBNAIL_SIZE = 320;

@implementation CDVEnterpriseWechat

#pragma mark "API"
- (void)pluginInitialize {
    
    self.agentId =@"";
    self.enterpriseId = @"" //[[self.commandDelegate settings] objectForKey:@"enterpriseid"];//
    self.schema = @"";
    NSLog(@"cordova-plugin-enterprise-wechat has been init: agentId: %@ enterpriseId:%@ schema:%@", self.agentId,self.enterpriseId,self.schema);
    
    if (self.agentId && self.enterpriseId && self.schema) {
       
        [WWKApi registerApp:self.schema corpId:self.enterpriseId agentId:self.agentId];
    }
}
- (void)isEWXAppInstalled:(CDVInvokedUrlCommand *)command
{
    [self.commandDelegate runInBackground:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:[WWKApi isAppInstalled]];

            [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId];
        });
        
    }];
   
}

- (void)share:(CDVInvokedUrlCommand *)command
{
    // if not installed
    if (![WWKApi isAppInstalled])
    {
        [self failWithCallbackID:command.callbackId withMessage:@"未安装企业微信"];
        return ;
    }

    // check arguments
    NSDictionary *params = [command.arguments objectAtIndex:0];
    if (!params)
    {
        [self failWithCallbackID:command.callbackId withMessage:@"参数格式错误"];
        return ;
    }

    // save the callback id
    self.currentCallbackId = command.callbackId;

//    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];


    // message or text?
    NSDictionary *message = [params objectForKey:@"message"];

    if (message)
    {
        // async
        [self.commandDelegate runInBackground:^{
            NSInteger type = [[params objectForKey:@"type"] integerValue];
            switch (type) {
                case CDVEWXSharingTypeText:
                    [self shareText:message];
                    break;
                case CDVEWXSharingTypeLink:
                    [self shareLink:message];
                    break;
                case CDVEWXSharingTypeFile:
                    [self shareFile:message];
                    break;
                
                case CDVEWXSharingTypeImage:
                    [self shareImage:message];
                    break;
                case CDVEWXSharingTypeVideo:
                    [self shareVideo:message];
                    break;
                    
                case CDVEWXSharingTypeForward:
                    [self shareForward:message];
                    break;
                 
                case CDVEWXSharingTypeMinApp:
                    [self shareImage:message];
                    break;
                default:
                    break;
            }
        }];
        
        

        
    }
    
}


/*! @brief 分享文字 */
- (void)shareText:(NSDictionary *)sender {
    WWKSendMessageReq *req = [[WWKSendMessageReq alloc] init];
    WWKMessageTextAttachment *attachment = [[WWKMessageTextAttachment alloc] init];
    attachment.text = [sender objectForKey:@"title"];
    req.attachment = attachment;
    dispatch_async(dispatch_get_main_queue(), ^{
        [WWKApi sendReq:req];
    });
}

/*! @brief 分享文件 */
- (void)shareFile:(NSDictionary *)sender {
    WWKSendMessageReq *req = [[WWKSendMessageReq alloc] init];
    WWKMessageFileAttachment *attachment = [[WWKMessageFileAttachment alloc] init];
    attachment.filename = @"Download.pdf";
    attachment.path = [sender objectForKey:@"webpageUrl"];
    req.attachment = attachment;
    dispatch_async(dispatch_get_main_queue(), ^{
        [WWKApi sendReq:req];
    });
}

/*! @brief 分享图片 */
- (void)shareImage:(NSDictionary *)sender {
    WWKSendMessageReq *req = [[WWKSendMessageReq alloc] init];
    WWKMessageImageAttachment *attachment = [[WWKMessageImageAttachment alloc] init];
    attachment.filename = [[sender objectForKey:@"webpageUrl"] lastPathComponent];;
    attachment.path = [sender objectForKey:@"webpageUrl"];
    req.attachment = attachment;
    dispatch_async(dispatch_get_main_queue(), ^{
        [WWKApi sendReq:req];
    });
}

/*! @brief 分享小视频 */
- (void)shareVideo:(NSDictionary *)sender {
    WWKSendMessageReq *req = [[WWKSendMessageReq alloc] init];
    WWKMessageVideoAttachment *attachment = [[WWKMessageVideoAttachment alloc] init];
    attachment.filename = [[sender objectForKey:@"webpageUrl"] lastPathComponent];
    attachment.path = [sender objectForKey:@"webpageUrl"] ;
    req.attachment = attachment;
    dispatch_async(dispatch_get_main_queue(), ^{
        [WWKApi sendReq:req];
    });
}

/*! @brief 分享链接 */
- (void)shareLink:(NSDictionary *)sender {
    WWKSendMessageReq *req = [[WWKSendMessageReq alloc] init];
    WWKMessageLinkAttachment *attachment = [[WWKMessageLinkAttachment alloc] init];
    attachment.title = [sender objectForKey:@"title"];
    attachment.summary = [sender objectForKey:@"description"];
    attachment.url = [sender objectForKey:@"webpageUrl"];
//    attachment.iconurl = [sender objectForKey:@"thumb"];
    attachment.icon = [self getNSDataFromURL:[sender objectForKey:@"thumb"]];
    req.attachment = attachment;
    dispatch_async(dispatch_get_main_queue(), ^{
        [WWKApi sendReq:req];
    });
    
}

/*! @brief 转发 */
- (void)shareForward:(NSDictionary *)sender {
    WWKSendMessageReq *req = [[WWKSendMessageReq alloc] init];
    WWKMessageGroupAttachment *attachment = [[WWKMessageGroupAttachment alloc] init];
    attachment.title = @"XXX的聊天记录";
    NSMutableArray *array = [NSMutableArray array];

    [array addObject:({
        WWKMessageAttachmentWrapper *wrapper = [[WWKMessageAttachmentWrapper alloc] init];
        wrapper.name = @"小明";
        wrapper.date = [[NSDate date] dateByAddingTimeInterval:-1000];
        wrapper.avatarUrl = @"http://p.qlogo.cn/bizmail/BDHWBviaRjEgxSn7E5dBwXMM0bibQVVFXe6C6dhtAdsGMu7vL7AuNpIQ/100";
        wrapper.attachment = ({
            WWKMessageTextAttachment *text = [[WWKMessageTextAttachment alloc] init];
            text.text = @"关注你我健康";
            text;
        });
        wrapper;
    })];
    
    [array addObject:({
        WWKMessageAttachmentWrapper *wrapper = [[WWKMessageAttachmentWrapper alloc] init];
        wrapper.name = @"小明";
        wrapper.date = [[NSDate date] dateByAddingTimeInterval:-950];
        wrapper.avatarUrl = @"http://p.qlogo.cn/bizmail/BDHWBviaRjEgxSn7E5dBwXMM0bibQVVFXe6C6dhtAdsGMu7vL7AuNpIQ/100";
        wrapper.attachment = ({
            WWKMessageImageAttachment *image = [[WWKMessageImageAttachment alloc] init];
            image.filename = @"test.gif";
            image.path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"gif"];
            image;
        });
        wrapper;
    })];
    
    [array addObject:({
        WWKMessageAttachmentWrapper *wrapper = [[WWKMessageAttachmentWrapper alloc] init];
        wrapper.name = @"小明";
        wrapper.date = [[NSDate date] dateByAddingTimeInterval:-930];
        wrapper.avatarUrl = @"http://p.qlogo.cn/bizmail/BDHWBviaRjEgxSn7E5dBwXMM0bibQVVFXe6C6dhtAdsGMu7vL7AuNpIQ/100";
        wrapper.attachment = ({
            WWKMessageLocationAttachment *loc = [[WWKMessageLocationAttachment alloc] init];
            loc.title = @"T.I.T创意园";
            loc.address = @"广东省广州市海珠区新港中路397号";
            loc.lat = 23.098837;
            loc.lng = 113.325119;
            loc;
        });
        wrapper;
    })];
    
    [array addObject:({
        WWKMessageAttachmentWrapper *wrapper = [[WWKMessageAttachmentWrapper alloc] init];
        wrapper.name = @"小码";
        wrapper.date = [[NSDate date] dateByAddingTimeInterval:-900];
        wrapper.avatarData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icon" ofType:@"jpg"]];
        wrapper.attachment = ({
            WWKMessageTextAttachment *text = [[WWKMessageTextAttachment alloc] init];
            text.text = @"学车找我不愁";
            text;
        });
        wrapper;
    })];
    
    [array addObject:({
        WWKMessageAttachmentWrapper *wrapper = [[WWKMessageAttachmentWrapper alloc] init];
        wrapper.name = @"小码";
        wrapper.date = [[NSDate date] dateByAddingTimeInterval:-850];
        wrapper.avatarData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icon" ofType:@"jpg"]];
        wrapper.attachment = ({
            WWKMessageFileAttachment *file = [[WWKMessageFileAttachment alloc] init];
            file.filename = @"Download.pdf";
            file.path = [[NSBundle mainBundle] pathForResource:@"About Downloads" ofType:@"pdf"];
            file;
        });
        wrapper;
    })];
    
    [array addObject:({
        WWKMessageAttachmentWrapper *wrapper = [[WWKMessageAttachmentWrapper alloc] init];
        wrapper.name = @"小码";
        wrapper.date = [[NSDate date] dateByAddingTimeInterval:-850];
        wrapper.avatarData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icon" ofType:@"jpg"]];
        wrapper.attachment = ({
            WWKMessageVideoAttachment *video = [[WWKMessageVideoAttachment alloc] init];
            video.filename = @"video.mp4";
            video.path = [[NSBundle mainBundle] pathForResource:@"video" ofType:@"mp4"];
            video;
        });
        wrapper;
    })];
    
    [array addObject:({
        WWKMessageAttachmentWrapper *wrapper = [[WWKMessageAttachmentWrapper alloc] init];
        wrapper.name = @"小码";
        wrapper.date = [[NSDate date] dateByAddingTimeInterval:-800];
        wrapper.avatarData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icon" ofType:@"jpg"]];
        wrapper.attachment = ({
            WWKMessageLinkAttachment *link = [[WWKMessageLinkAttachment alloc] init];
            link.title = @"链接标题";
            link.summary = @"链接介绍";
            link.url = @"http://www.tencent.com";
            link.icon = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icon" ofType:@"jpg"]];
            link;
        });
        wrapper;
    })];
    
    attachment.contents = array;
    req.attachment = attachment;
    dispatch_async(dispatch_get_main_queue(), ^{
        [WWKApi sendReq:req];
    });
}





#pragma mark "WWKApiDelegate"

- (void)onResp:(WWKBaseResp *)resp {
    /*! @brief 所有通过sendReq发送的SDK请求的结果都在这个函数内部进行异步回调
     * @param resp SDK处理请求后的返回结果 需要判断具体是哪项业务的回调
     */
    NSMutableString *extra = [NSMutableString string];
    
    /* 选择联系人的回调 */
    if ([resp isKindOfClass:[WWKPickContactResp class]]) {
        WWKPickContactResp *r = (WWKPickContactResp *)resp;
        for (int i = 0; i < MIN(r.contacts.count, 5); ++i) {
            if (extra.length) [extra appendString:@"\n"];
            [extra appendFormat:@"%@<%@>", [r.contacts[i] name], [r.contacts[i] email]];
        }
        if (r.contacts.count > 5) {
            [extra appendString:@"\n…"];
        }
    }
    
    /* SSO的回调 */
    if ([resp isKindOfClass:[WWKSSOResp class]]) {
        WWKSSOResp *r = (WWKSSOResp *)resp;
        [extra appendFormat:@"%@ for %@", r.code, r.state];
    }
    
    if (extra.length) [extra insertString:@"\n\n" atIndex:0];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"返回结果" message:[NSString stringWithFormat:@"错误码：%d\n错误信息：%@%@", resp.errCode, resp.errStr, extra] preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:alert animated:YES completion:nil];
}

#pragma mark "CDVPlugin Overrides"

- (void)handleOpenURL:(NSNotification *)notification
{
    NSURL* url = [notification object];
    
    if ([url isKindOfClass:[NSURL class]] && [url.scheme isEqualToString:self.agentId])
    {
     
        [WWKApi handleOpenURL:url delegate:self];
        
    }
}

- (NSData *)getNSDataFromURL:(NSString *)url
{
    NSData *data = nil;

    if ([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"])
    {
        data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
    }
    else if ([url hasPrefix:@"data:image"])
    {
        // a base 64 string
        NSURL *base64URL = [NSURL URLWithString:url];
        data = [NSData dataWithContentsOfURL:base64URL];
    }
    else if ([url rangeOfString:@"temp:"].length != 0)
    {
        url =  [NSTemporaryDirectory() stringByAppendingPathComponent:[url componentsSeparatedByString:@"temp:"][1]];
        data = [NSData dataWithContentsOfFile:url];
    }
    else
    {
        // local file
        url = [[NSBundle mainBundle] pathForResource:[url stringByDeletingPathExtension] ofType:[url pathExtension]];
        data = [NSData dataWithContentsOfFile:url];
    }

    return data;
}

- (UIImage *)getUIImageFromURL:(NSString *)url
{
    NSData *data = [self getNSDataFromURL:url];
    UIImage *image = [UIImage imageWithData:data];

    if (image.size.width > MAX_THUMBNAIL_SIZE || image.size.height > MAX_THUMBNAIL_SIZE)
    {
        CGFloat width = 0;
        CGFloat height = 0;

        // calculate size
        if (image.size.width > image.size.height)
        {
            width = MAX_THUMBNAIL_SIZE;
            height = width * image.size.height / image.size.width;
        }
        else
        {
            height = MAX_THUMBNAIL_SIZE;
            width = height * image.size.width / image.size.height;
        }

        // scale it
        UIGraphicsBeginImageContext(CGSizeMake(width, height));
        [image drawInRect:CGRectMake(0, 0, width, height)];
        UIImage *scaled = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return scaled;
    }

    return image;
}

- (void)successWithCallbackID:(NSString *)callbackID
{
    [self successWithCallbackID:callbackID withMessage:@"OK"];
}

- (void)successWithCallbackID:(NSString *)callbackID withMessage:(NSString *)message
{
    CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];
    [self.commandDelegate sendPluginResult:commandResult callbackId:callbackID];
}

- (void)failWithCallbackID:(NSString *)callbackID withError:(NSError *)error
{
    [self failWithCallbackID:callbackID withMessage:[error localizedDescription]];
}

- (void)failWithCallbackID:(NSString *)callbackID withMessage:(NSString *)message
{
    CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:message];
    [self.commandDelegate sendPluginResult:commandResult callbackId:callbackID];
}

@end
